package com.smt.common.utils;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.smt.modules.bus.entity.BillEntity;
import com.smt.modules.bus.entity.GradeEntity;
import com.smt.modules.bus.entity.MemberUserEntity;
import com.smt.modules.bus.service.BillService;
import com.smt.modules.bus.service.GradeService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 通用账单和积分添加
 *
 * @author zhangyi
 * @date 2018/10/18 15:57
 */
@Component
public class GradeUtil {
    @Autowired
    private GradeService gradeService;
    @Autowired
    private BillService billService;


    /**
     * 日常任务更新积分信息
     *
     * @param in 添加的积分数
     * @param memberUserEntity 用户实体信息
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateGrade(MemberUserEntity memberUserEntity,Long billId){
        boolean insert = false;
        boolean result = false;
        if(billId != null){
            GradeEntity gradeEntity = new GradeEntity();
            GradeEntity gradeEntity1 = gradeService.selectOne(new EntityWrapper<GradeEntity>()
                    .eq("member_id", memberUserEntity.getUserId()));
            //现有积分
            Integer integral = gradeEntity1.getIntegral();
            BillEntity billIn = billService.selectById(billId);
            gradeEntity.setIntegral(billIn.getAmount()+integral);
            gradeEntity.setMemberId(memberUserEntity.getUserId());
            gradeEntity.setCreateTime(DateTime.now().toDate());
            result = gradeService.update(gradeEntity, new EntityWrapper<GradeEntity>()
                    .eq("member_id", memberUserEntity.getUserId()));
            //更新账单状态
            BillEntity billEntity = new BillEntity();
            billEntity.setId(billId);
            billEntity.setIsReward(2);
            insert = billService.updateById(billEntity);
        }else{
            insert = false;
        }
        return (result && insert);
    }

}
